package com.qishen.operation.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qishen.operation.mapper.LoginMapper;
import com.qishen.operation.service.LoginService;
import com.san.model.operation.dtos.LoginDto;
import com.san.model.operation.pojos.TbEmployee;
import com.san.model.operation.vo.LoginVo;

import com.utils.common.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, TbEmployee> implements LoginService {
    @Autowired
    LoginMapper loginMapper;

    @Override
    public LoginVo login(LoginDto dto) {
        //校验参数
        if (StringUtils.isEmpty(dto.getUsername()) && StringUtils.isEmpty(dto.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        //查询数据库用户信息
        List<TbEmployee> list = list(Wrappers.<TbEmployee>lambdaQuery().eq(TbEmployee::getUsername, dto.getUsername()));
        if (list != null && list.size() == 1) {
            TbEmployee tbUser = list.get(0);

            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(dto.getPassword(), tbUser.getPassword());
            if (matches) {
                //返回数据
                LoginVo loginVO = new LoginVo();
               // loginVO.setToken(AppJwtUtil.getToken(tbUser.getId().longValue()));
                loginVO.setToken(JwtUtil.createJWT(tbUser.getUsername(),null));
                loginVO.setUsername(tbUser.getUsername());
                return loginVO;
            }
        }
        return null;
    }
}
